package features.advance.ch2;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;
import java.net.URL;

public class SAXTest {
    public static void main(String[] args) throws Exception {
        String url;
        if (args.length == 0){
            url = "http://www.w3c.org";
            System.out.println("Using "+url);
        }else url = args[0];

        DefaultHandler defaultHandler = new DefaultHandler(){
            @Override
            public void startElement(String namespaceURI, String lname, String qname,
                                     Attributes attrs){
                if (lname.equals("a") && attrs != null){
                    for (int i = 0; i < attrs.getLength(); i++) {
                        String localName = attrs.getLocalName(i);
                        if (localName.equals("href")) System.out.println(attrs.getValue(i));
                    }
                }
            }
        };
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        InputStream inputStream = new URL(url).openStream();
        saxParser.parse(inputStream,defaultHandler);
        inputStream.close();
    }

}
